"use client"

import { useState, useEffect, useRef } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Play, Heart, MessageSquare } from "lucide-react"
import { toast } from "@/components/ui/use-toast"
import { useParams } from "next/navigation"
import { fetchAlbum, toggleFavorite } from "@/lib/api-client"
import { usePlayer } from "@/contexts/player-context"
import CommentSection from "@/components/comments/shared/comment-section"
import { SongCard } from "@/components/song-card"
import { MoreOptionsMenu } from "@/components/more-options-menu"
import type { Album } from "@/types/album"
import type { Song } from "@/types/song"
import { cn } from "@/lib/utils"

export default function AlbumPage() {
  const [album, setAlbum] = useState<Album | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isCollected, setIsCollected] = useState(false)
  const [showFullDescription, setShowFullDescription] = useState(false)
  const [userId, setUserId] = useState<number>()
  const [currentPlayingSongId, setCurrentPlayingSongId] = useState<number | null>(null)
  const { id } = useParams()
  const { playSong, playQueue, state } = usePlayer()

  const commentSectionRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // Get userId from localStorage
    const storedUserId = localStorage.getItem("userId")
    if (storedUserId) {
      const userIdAsNumber = +storedUserId;
      setUserId(userIdAsNumber);
    }

    const getAlbum = async () => {
      try {
        setIsLoading(true)
        const data = await fetchAlbum(id as string,userId)
        setAlbum(data)
        setIsCollected(data.isLiked)
      } catch (err) {
        console.error("Failed to fetch album:", err)
        setError("加载专辑数据失败")
      } finally {
        setIsLoading(false)
      }
    }

    // Only run on the client side to avoid hydration mismatches
    if (typeof window !== "undefined") {
      getAlbum()
    }
  }, [id])

  // Update currently playing song when player state changes
  useEffect(() => {
    if (state.currentSong) {
      setCurrentPlayingSongId(state.currentSong.id)
    }
  }, [state.currentSong])

  const handlePlayAll = () => {
    if (album && album.songs) {
      // Transform album songs to include necessary player information
      const songsWithMetadata = album.songs.map((song) => ({
        ...song,
        artist: album.artists,
        coverImage: album.cover,
        url: song.url || `/api/stream/${song.id}`, // Fallback to stream endpoint if no direct URL
      }))
      // Play all songs in queue
      playQueue(songsWithMetadata)
    }
  }

  const handlePlaySong = (songId: number) => {
    if (album && album.songs) {
      const song = album.songs.find((s) => s.id === songId)
      if (song) {
        const songWithMetadata = {
          ...song,
          artists: album.artists,
          cover: album.cover,
          url: song.url,
        }
        playSong(songWithMetadata as Song)
        toast({
          title: "开始播放",
          description: `${song.title} - ${album.artists}`,
        })
      }
    }
  }

  const handleCollect = async () => {
    try {
      if (!userId) {
        toast({
          title: "操作失败",
          description: "用户未登录，请先登录！",
        })
        return
      }

      if (album !== null) {
        await toggleFavorite({
          contentType: "album",
          contentId: id,
          userId: userId,
          action: !album.isLiked,
        })
        album.isLiked = !album.isLiked
        setIsCollected(album.isLiked)
        toast({
          title: !album.isLiked ? "收藏成功" : "已取消收藏",
          description: `专辑《${album?.title}》${!album.isLiked ? "已添加到收藏" : "已从收藏中移除"}`,
        })
      }
    } catch (error) {
      console.error("Failed to update collection:", error)
      toast({
        title: "操作失败",
        description: "请稍后重试",
      })
    }
  }

  const scrollToComments = () => {
    commentSectionRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  if (isLoading) {
    return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">加载中...</p>
          </div>
        </div>
    )
  }

  if (error || !album) {
    return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <p className="text-destructive mb-4">加载失败</p>
            <Button onClick={() => window.location.reload()}>重试</Button>
          </div>
        </div>
    )
  }

  // Prepare songs with album information for SongCard
  const songsWithAlbumInfo: Song[] = album.songs.map((song) => ({
    ...song,
    artists: album.artists,
    cover: song.cover || album.cover,
  }))

  return (
      <div className="min-h-screen bg-background pb-32">
        <div className="relative">
          <div className="absolute inset-0 bg-gradient-to-b from-background/0 to-background" />
          <div className="container mx-auto px-4 py-8">
            {/* Separate album cover and info into different sections */}
            <div className="flex flex-col md:flex-row gap-8">
              {/* Album cover section */}
              <div className="relative w-64 h-64 flex-shrink-0 z-10">
                <Image
                    src={album.cover || "/placeholder.svg"}
                    alt={`Album cover for ${album.title}`}
                    fill
                    className="object-cover rounded-lg"
                />
              </div>

              {/* Album info and actions section */}
              <div className="flex-1 min-w-0 z-20">
                <div className="space-y-4">
                  <div className="inline-block px-2 py-1 rounded bg-primary/10 text-primary text-sm">{album.type}</div>
                  <h1 className="text-3xl font-bold">{album.title}</h1>
                  <div className="text-lg">歌手：{album.artists}</div>

                  <div className="space-y-2 text-sm text-muted-foreground">
                    <div>发行时间：{album.releaseDate}</div>
                    <div>发行公司：{album.company}</div>
                    <div>专辑风格：{album.genre}</div>
                  </div>
                </div>

                {/* Action buttons in a separate container */}
                <div className="flex items-center gap-4 mt-6">
                  <Button className="gap-2 hover:bg-primary/90" onClick={handlePlayAll}>
                    <Play className="h-4 w-4" />
                    播放全部
                  </Button>
                  <Button
                      variant="outline"
                      className={cn("gap-2 hover:bg-accent", isCollected && "text-red-500 hover:text-red-500")}
                      onClick={handleCollect}
                  >
                    <Heart className={cn("h-4 w-4", isCollected && "fill-current")} />
                    {isCollected ? "已收藏" : "收藏"}
                  </Button>
                  <Button variant="outline" className="gap-2 hover:bg-accent" onClick={scrollToComments}>
                    <MessageSquare className="h-4 w-4" />
                    评论
                  </Button>
                  <MoreOptionsMenu
                      resource={{
                        id: album.id,
                        type: "album",
                        title: album.title,
                        cover: album.cover,
                        artist: album.artists,
                      }}
                      onDownload={() => {
                        toast({
                          title: "下载中",
                          description: `正在下载专辑: ${album.title}`,
                        })
                      }}
                      onAddToPlaylist={() => {
                        toast({
                          title: "添加到歌单",
                          description: "请选择要添加到的歌单",
                        })
                      }}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Song list using SongCard */}
        <div className="container mx-auto px-4 py-8">
          <div className="grid grid-cols-[1fr_300px] gap-8">
            <div className="space-y-6">
              <div className="bg-card rounded-lg p-4">
                <h2 className="text-xl font-semibold mb-4">歌曲列表</h2>
                <div className="space-y-2">
                  {songsWithAlbumInfo.map((song, index) => (
                      <div key={song.id} className="flex items-center">
                        <span className="w-8 text-center text-muted-foreground">{index + 1}</span>
                        <div className="flex-1">
                          <SongCard
                              index={index+1}
                              song={song}
                              userId={userId || undefined}
                              onPlay={handlePlaySong}
                              isPlaying={currentPlayingSongId === song.id}
                              className="hover:bg-accent/50"
                          />
                        </div>
                      </div>
                  ))}
                </div>
              </div>

              {/* Add comment section */}
              <div ref={commentSectionRef} className="mt-8 pt-8 border-t">
                <h2 className="text-xl font-bold mb-6">评论</h2>
                <CommentSection contentId={id as string} contentType="album" />
              </div>
            </div>

            <div className="space-y-6">
              <div className="bg-card rounded-lg p-4">
                <h3 className="font-medium mb-2">专辑简介</h3>
                {album.description && (<div >
                <p className="text-sm text-muted-foreground whitespace-pre-line">
                  {showFullDescription ? album.description : `${album.description.slice(0, 100)}...`}
                </p>
                { album.description.length > 100 && (
                    <Button
                        variant="link"
                        className="p-0 h-auto text-sm"
                        onClick={() => setShowFullDescription(!showFullDescription)}
                    >
                      {showFullDescription ? "收起" : "展开"}
                    </Button>
                )}</div>)}
              </div>
            </div>
          </div>
        </div>
      </div>
  )
}

